package cn.tedu._03vehicle.base.exception;

import cn.tedu._03vehicle.base.response.JsonResult;
import cn.tedu._03vehicle.base.response.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

/**
 * 全局异常处理类
 */
//@ControllerAdvice
@Slf4j
@RestControllerAdvice//@ControllerAdvice + @ResponseBody
public class GlobalExceptionHandler {
    /**
     * ExceptionHandler注解:
     * 1.添加在方法上,标识该方法为异常处理方法;
     */
    /**
     * 1.第1个异常处理方法:可以处理IllegalArgumentException异常的处理方法;
     */
    @ExceptionHandler
    public JsonResult doHandleIllegalArgumentException(IllegalArgumentException ex){
        String data = ex.getMessage();
        log.error("doHandleIllegalArgumentException:" + data);

        //{"state":3000, "message":"操作失败", "data": "id值非法!"}
        return new JsonResult(StatusCode.OPERATION_FAILED, data);
    }

    /**
     * 2.第2个异常处理方法:可以处理所有RuntimeException及其子类异常的处理方法;
     */
    @ExceptionHandler
    public JsonResult doHandleRuntimeException(RuntimeException ex){
        String data = ex.getMessage();
        log.error("doHandleRuntimeException:" + data);

        return new JsonResult(StatusCode.OPERATION_FAILED, data);
    }

    /**
     * 3.第3个异常处理方法:可以处理所有异常的处理方法;
     */
    @ExceptionHandler
    public JsonResult doHandleThrowable(Throwable ex){
        String data = ex.getMessage();
        log.error("doHandleThrowable:" + data);

        return new JsonResult(StatusCode.THROWABLE_ERROR, data);
    }

    /**
     * 对封装类参数的异常进行处理
     */
    @ExceptionHandler
    public JsonResult doHandleMethodArgumentNotValidException(MethodArgumentNotValidException exception){
        String data = exception.getFieldError().getDefaultMessage();
        log.error("doHandleMethodArgumentNotValidException:" + data);
        return new JsonResult(StatusCode.VALIDATE_ERROR, data);
    }

    @ExceptionHandler
    public JsonResult doHandleConstraintViolationException(ConstraintViolationException ex){
        String data = ex.getConstraintViolations().iterator().next().getMessage();
        log.error("doHandleConstraintViolationException:" + data);
        return new JsonResult(StatusCode.VALIDATE_ERROR, data);
    }
}
